# -*- coding:utf-8 -*-
from django.shortcuts import render_to_response
from django.core.exceptions import ObjectDoesNotExist

from runtime.utils.msg_tools import get_msg_key, get_msg, render_msg_content, get_msg_body

from autoreply.models import Index, News, Text

# Create your views here.
def run(request_from_client, type='text'):
	global request
	request = request_from_client
	if type == 'text':
		return reply_to_text()
	else:
		msg_get = get_msg(request)
		reply_key = msg_get.Event.text
		return get_reply(reply_key)

def reply_to_text():
	msg_get = get_msg(request)
	msg_body = get_msg_body(msg_get)
	msg_key = get_msg_key(msg_get)

	if msg_body:
		return get_reply(msg_body)
	else:
		return get_reply(msg_key)
	


def get_reply(reply_key):
	msg_key = reply_key
	text_str = get_text_response(request, msg_key)
	if text_str:
		return text_str
	else:
		pass

	try:
		return get_article_list(request, msg_key)
	except ObjectDoesNotExist:
		keyring = Index.objects.all()
		key_str = str()
		for key in keyring:
			key_str += key.msg_key
			key_str += '\n'
		return render_msg_content('text', key_str)



def get_text_response(request, msg_key):
#	try:
#		key = Index.objects.get(msg_key=msg_key)
#	except ObjectDoesNotExist:
#		return ''
	try:
		msg_text = Text.objects.get(msg_key=msg_key)
	except ObjectDoesNotExist:
		return ''
	return render_msg_content('text', msg_text.content)



def get_article_list(request, msg_body):
	try:
		key = Index.objects.get(msg_key=msg_body)
	except ObjectDoesNotExist:
		return render_msg_content('text', 'No Key!')
	article_list = News.objects.filter(msg_key=key)
	counter = 0
	send_list = list()
	for article_item in article_list:
		counter += 1
		if counter <= 10:
			item = Article(request, article_item)
			send_list.append(item)
		else:
			break

	msg_content = {
		'msg_type':'news',
		'article_count': counter,
		'articles':send_list,
	}
	return msg_content

		
class Article():
	def __init__(self, request, article_item,):
		self.__request = request
		self.__article = article_item

		self.title = self.__article.title
		self.description = self.__article.description
		self.url = self.__gen_url()
		pic_url = self.__gen_url(is_pic=True)
		if pic_url:
			self.pic_url = pic_url



	def __gen_url(self, is_pic=False):
		root_url = 'https://' + self.__request.get_host()
		if not is_pic:
			url = root_url + '/article/' + str(self.__article.id)
		else:
			pic_url = unicode(self.__article.pic_url)
			if not pic_url:
				return ''
			url = root_url + '/media' +pic_url[1:]
		return url


def get_article(request, article_id):
	article = News.objects.get(id=article_id)
	title = article.title
	content = article.content

	return render_to_response('article.html', {'title':title, 'content':content,})